from fastapi import APIRouter, Depends
from ..models import Dept
from ..schemas import DeptInSchema, DeptOutSchema, DeptOutTreeSchema
from src.utils.common_response import APIResponse
from typing import List

router = APIRouter()


@router.get("/depts", description='查询所有部门')
async def get_dept_list():
    depts = await Dept.filter(is_delete=False, pid=None).all().prefetch_related('children')
    dept_dict = [await DeptOutSchema.from_orm_recursive(dept) for dept in depts]
    return APIResponse(result=dept_dict)


@router.post("/depts", description="新增部门")
async def add_dept(dept: DeptInSchema):
    print("dept", dept)
    dept = await Dept.create(**dept.dict())
    if dept:
        return APIResponse(msg="新增部门成功")
    else:
        raise Exception('新增部门失败')


@router.delete("/depts", description="删除部门")
async def delete_dept(ids: List[int]):
    print("ids:::", ids)
    await Dept.filter(id__in=ids).update(is_delete=True)
    return APIResponse(msg="删除部门成功")


@router.get("/dept/{dept_id}", description="查询单个部门")
async def get_dept(dept_id: int):
    dept = await Dept.filter(id=dept_id).first()
    dept_dict = await DeptOutSchema.from_orm_recursive(dept)
    return APIResponse(msg='部门查询成功', result=dept_dict)


@router.put("/depts/{dept_id}", description="修改一个部门")
async def put_dept(dept_id: int, dept: DeptInSchema):
    dept = await Dept.filter(id=dept_id).update(**dept.dict())
    return APIResponse(msg='部门修改成功')


@router.get('/tree/depts', description='查询部门树')
async def get_dept_list_tree():
    menus = await Dept.filter(is_delete=False, pid=None).all().prefetch_related()
    menu_dict = [await DeptOutTreeSchema.from_orm_recursive(menu) for menu in menus]
    return APIResponse(result=menu_dict)
